#ifndef HTTP_HANDLER_HPP
#define HTTP_HANDLER_HPP

#include "DBhandler.hpp"
#include "httplib.h"
#include "json.hpp"
#include "password_hash.hpp"
#include "config_manager.hpp"

namespace xzt
{
    using namespace httplib;
    using json = nlohmann::json;

// 设定前端源文件相对于图片文件所在目录的相对路径
#define FRONT_SRC_TO_PHOTO_DIR "../../../backend/source/photos/"

    class PhotoHttpHandler
    {
    public:
        // 上传图片
        static void Upload(const Request &req, Response &res)
        {
            try
            {
                // Extract multipart/form-data
                httplib::MultipartFormData file = req.get_file_value("image");
                std::string title = req.get_file_value("title").content;
                std::string category = req.get_file_value("category").content;
                std::string user_id_s = req.get_file_value("user_id").content;
                int user_id = std::stoi(user_id_s);

                // 创建PhotoDataType对象
                PhotoDataType photo;
                photo.user_id = std::to_string(user_id);
                photo.title = title;
                photo.category = category;
                // 填充图片二进制数据
                photo.image_binary.resize(file.content.size());
                std::copy(file.content.begin(), file.content.end(), photo.image_binary.begin());
                LOG_INFO("Upload: title = %s, category = %s, user_id = %s, image_binary.size() = %d",
                         title.c_str(), category.c_str(), user_id_s.c_str(), photo.image_binary.size());

                // 保存图片
                if (!PhotoDBHandler::SavePhoto(photo))
                {
                    res.status = 500;
                    res.set_content(R"({"error": "Failed to save photo"})", "application/json");
                    return;
                }

                res.set_content(R"({"message": "Photo uploaded successfully"})", "application/json");
            }
            catch (const std::exception &ex)
            {
                res.status = 400;
                res.set_content(R"({"error": ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }

        // 获取所有图片信息
        static void GetAllPhotos(const Request &req, Response &res)
        {
            try
            {
                // 根据查询参数选择排序方式，默认按时间排序
                std::string sort = req.get_param_value("sort");
                if (sort.empty())
                {
                    sort = "time";
                }
                LOG_INFO("GetAllPhotos: sort by %s", sort.c_str());

                std::vector<PhotoDataType> photos;

                if (sort == "likes")
                {
                    photos = PhotoDBHandler::GetAllPhotos_OrderByLikes(); // 按点赞数排序
                }
                else
                {
                    photos = PhotoDBHandler::GetAllPhotos_OrderByTime(); // 按时间排序（默认）
                }

                // 构造 JSON 响应数据
                json result = json::array();
                for (const auto &photo : photos)
                {
                    json item;
                    item["photo_id"] = photo.photo_id;
                    item["user_id"] = photo.user_id;
                    item["title"] = photo.title;
                    item["category"] = photo.category;
                    item["likes"] = photo.likes;
                    item["created_at"] = photo.created_at;
                    // 图片路径（可用于前端加载图片）
                    std::string image_name = photo.image_path.substr(photo.image_path.find_last_of("/") + 1);
                    const auto& config = ConfigManager::getInstance();
                    item["url"] = config.getURL() + "/photos/" + image_name; // 图片路径（可用于前端加载图片） -- 例如：2.jpg
                    result.push_back(item);
                }

                // 返回 JSON 数据
                res.set_content(result.dump(), "application/json");
            }
            catch (const std::exception &ex)
            {
                // 错误处理：返回错误信息
                res.status = 500;
                res.set_content(R"({"error": ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }

        // 获取指定用户的图片信息
        static void GetPhotosByUser(const Request &req, Response &res)
        {
            // 注意对于httplib库，提取路径中的参数不能用req.matches[1]
            auto user_id = req.path_params.at("user_id");

            // 后续处理
            try
            {
                // 从数据库中获取用户的图片列表
                std::vector<PhotoDataType> photos = PhotoDBHandler::GetPhotosByUserID(user_id);
                LOG_INFO("GetPhotosByUser: photos.size() = %d", photos.size());

                // 构造 JSON 响应数据
                json result = json::array();
                for (const auto &photo : photos)
                {
                    json item;
                    item["photo_id"] = photo.photo_id;
                    item["user_id"] = photo.user_id;
                    item["title"] = photo.title;
                    item["category"] = photo.category;
                    item["likes"] = photo.likes;
                    item["created_at"] = photo.created_at;
                    // 图片路径（可用于前端加载图片）
                    std::string image_name = photo.image_path.substr(photo.image_path.find_last_of("/") + 1);
                    const auto& config = ConfigManager::getInstance();
                    item["url"] = config.getURL() + "/photos/" + image_name; // 图片路径（可用于前端加载图片） -- 例如：2.jpg
                    result.push_back(item);
                }

                // 返回 JSON 数据
                res.set_content(result.dump(), "application/json");
            }
            catch (const std::exception &ex)
            {
                // 错误处理：返回错误信息
                res.status = 500;
                res.set_content(R"({"error": ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }

        // 获取单张图片详情
        static void GetPhoto(const Request &req, Response &res)
        {
            try
            {
                // 提取路径参数 photo_id
                auto photo_id = req.path_params.at("photo_id");

                // 从数据库和文件系统获取图片详情
                std::string image_path = PHOTO_DIR + photo_id + ".jpg";
                PhotoDataType photo = PhotoDBHandler::GetPhoto(image_path);
                if (!photo) // 查询失败
                {
                    res.status = 404;
                    res.set_content(R"({"error": "Photo not found"})", "application/json");
                    return;
                }

                // 构造 JSON 响应数据
                json result;
                result["photo_id"] = photo.photo_id;
                result["title"] = photo.title;
                result["category"] = photo.category;
                result["likes"] = photo.likes;
                // 图片路径（可用于前端加载图片）
                std::string image_name = photo.image_path.substr(photo.image_path.find_last_of("/") + 1);
                const auto& config = ConfigManager::getInstance();
                result["url"] = config.getURL() + "/photos/" + image_name; // 图片路径（可用于前端加载图片） -- 例如：2.jpg

                // 返回 JSON 数据
                res.set_content(result.dump(), "application/json");
            }
            catch (const std::exception &ex)
            {
                // 错误处理：返回错误信息
                res.status = 500;
                res.set_content(R"({"error": ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }

        // 获取指定分类下所有图片信息
        static void GetPhotosByCategory(const Request &req, Response &res)
        {
            try
            {
                // 提取路径参数 category
                auto category = req.path_params.at("category");
                // 提取查询参数 sort
                auto sort = req.get_param_value("sort");
                if (sort.empty())
                {
                    sort = "time";
                }

                // 从数据库中获取指定分类的图片列表
                std::vector<PhotoDataType> photos = (sort == "likes") ? PhotoDBHandler::GetPhotosByCategory_OrderByLikes(category) : PhotoDBHandler::GetPhotosByCategory_OrderByTime(category);
                LOG_INFO("GetPhotosByCategory: category = %s, order by %s, photos.size() = %d",
                         category.c_str(), sort.c_str(), photos.size());

                // 构造 JSON 响应数据
                json result = json::array();
                for (const auto &photo : photos)
                {
                    json item;
                    item["photo_id"] = photo.photo_id;
                    item["user_id"] = photo.user_id;
                    item["title"] = photo.title;
                    item["category"] = photo.category;
                    item["likes"] = photo.likes;
                    // 图片路径（可用于前端加载图片）
                    std::string image_name = photo.image_path.substr(photo.image_path.find_last_of("/") + 1);
                    const auto& config = ConfigManager::getInstance();
                    item["url"] = config.getURL() + "/photos/" + image_name; // 图片路径（可用于前端加载图片） -- 例如：2.jpg
                    result.push_back(item);
                }

                // 返回 JSON 数据
                res.set_content(result.dump(), "application/json");
            }
            catch (const std::exception &ex)
            {
                // 错误处理：返回错误信息
                res.status = 500;
                res.set_content(R"({"error": ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }

        // 点赞指定图片
        static void LikePhoto(const Request &req, Response &res)
        {
            try
            {
                // 提取路径参数 photo_id 和请求参数 user_id
                auto photo_id_s = req.path_params.at("photo_id");
                size_t photo_id = std::stoul(photo_id_s);
                size_t user_id = std::stoul(req.get_file_value("user_id").content);

                // 调用 PhotoDBHandler 的 LikePhoto 方法进行点赞
                if (!PhotoDBHandler::LikePhoto(photo_id, user_id))
                {
                    // 如果点赞失败（例如用户已经点过赞）
                    res.status = 400;
                    res.set_content(R"({"error": "Failed to like photo or already liked"})", "application/json");
                    return;
                }

                // 点赞成功
                res.set_content(R"({"message": "Photo liked successfully"})", "application/json");
            }
            catch (const std::exception &ex)
            {
                // 错误处理：返回错误信息
                res.status = 400;
                res.set_content(R"({"error": ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }

        // 删除指定图片
        static void DeletePhoto(const Request &req, Response &res)
        {
            try
            {
                // 提取路径参数 photo_id
                std::string photo_id = req.path_params.at("photo_id");

                // 从数据库和文件系统删除图片
                std::string image_path = PHOTO_DIR + photo_id + ".jpg";
                if (!PhotoDBHandler::DeletePhoto(image_path))
                {
                    // 如果删除失败
                    res.status = 500;
                    res.set_content(R"({"error": "Failed to delete photo"})", "application/json");
                    return;
                }

                // 删除成功
                res.set_content(R"({"message": "Photo deleted successfully"})", "application/json");
            }
            catch (const std::exception &ex)
            {
                // 错误处理：返回错误信息
                res.status = 400;
                res.set_content(R"({"error": ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }
    };

    class UserHttpHandler
    {
    public:
        // 注册新用户
        static void Register(const Request &req, Response &res)
        {
            try
            {
                // 提取请求参数
                std::string username = req.get_file_value("username").content;
                std::string password = req.get_file_value("password").content;
                std::string email = req.get_file_value("email").content;
                if(username.empty()||password.empty()||email.empty())
                {
                    // 注册失败
                    res.status = 400;
                    res.set_content(R"({"error": "请检查用户名、密码、邮箱是否为空"})", "application/json");
                    return;
                }

                // 调用 DBHandler 的 RegisterUser 方法进行注册
                UserDataType user(username, password, email);
                int ret = UserDBHandler::RegisterUser(user);
                if (ret == 0)
                {
                    // 注册失败
                    res.status = 400;
                    res.set_content(R"({"error": "Failed to register user"})", "application/json");
                    return;
                }
                else if (ret == -1)
                {
                    // 用户名已存在
                    res.status = 400;
                    res.set_content(R"({"error": "Username already exists"})", "application/json");
                    return;
                }

                // 注册成功 -- ret==1
                res.set_content(R"({"message": "User registered successfully"})", "application/json");
            }
            catch (const std::exception &ex)
            {
                // 错误处理：返回错误信息
                res.status = 400;
                res.set_content(R"({"error": ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }

        // 登录用户
        static void Login(const Request &req, Response &res)
        {
            try
            {
                // 提取请求参数
                std::string username = req.get_file_value("username").content;
                std::string password = req.get_file_value("password").content;

                int user_id = UserDBHandler::Verify(username, password);
                if (user_id == 0)
                {
                    // 如果登录失败（例如用户名或密码错误）
                    res.status = 401;
                    res.set_content(R"({"error": "Invalid username or password"})", "application/json");
                    return;
                }
                else if (user_id == -1)
                {
                    // 如果登录失败（例如用户被封禁）
                    res.status = 403;
                    res.set_content(R"({"error": "User is banned"})", "application/json");
                    return;
                }
                // 登录成功，返回用户ID
                res.set_content(R"({"user_id": ")" + std::to_string(user_id) + R"("})", "application/json");
            }
            catch (const std::exception &ex)
            {
                // 错误处理：返回错误信息
                res.status = 400;
                res.set_content(R"({"error": ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }

        // 获取用户个人信息
        static void GetUserInfo(const Request &req, Response &res)
        {
            try
            {
                // 提取路径参数 user_id
                auto user_id_s = req.path_params.at("user_id");
                size_t user_id = std::stoul(user_id_s);

                UserDataType user = UserDBHandler::GetUserByID(user_id);
                if (!user) // 查询失败
                {
                    res.status = 404;
                    res.set_content(R"({"error": "User not found"})", "application/json");
                    return;
                }

                // 构造 JSON 响应数据
                // 密码数据不做返回
                json result;
                result["user_id"] = user.user_id;
                result["username"] = user.username;
                result["email"] = user.email;
                result["created_at"] = user.created_at;

                // 返回 JSON 数据
                res.set_content(result.dump(), "application/json");
            }
            catch (const std::exception &ex)
            {
                // 错误处理：返回错误信息
                res.status = 500;
                res.set_content(R"({"error": ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }

        // 修改用户个人信息
        static void UpdateUserInfo(const Request &req, Response &res)
        {
            try
            {
                // 提取路径参数 user_id
                auto user_id_s = req.path_params.at("user_id");
                size_t user_id = std::stoul(user_id_s);

                // 提取请求参数
                std::string username = req.get_file_value("username").content;
                std::string password = req.get_file_value("password").content;
                std::string email = req.get_file_value("email").content;

                // 调用 DBHandler 的 UpdateUserInfo 方法进行更新
                UserDataType user(username, password, email);
                int ret = UserDBHandler::UpdateUser(user_id, user);
                if (ret == -1)
                {
                    // 更新失败，用户ID不存在
                    res.status = 400;
                    res.set_content(R"({"error": "User not found by user_id"})", "application/json");
                    return;
                }
                else if (ret == 0)
                {
                    // 更新失败，Update时username重名
                    res.status = 400;
                    res.set_content(R"({"error": "Username already exists"})", "application/json");
                    return;
                }

                // 更新成功
                res.set_content(R"({"message": "User info updated successfully"})", "application/json");
            }
            catch (const std::exception &ex)
            {
                // 错误处理：返回错误信息
                res.status = 400;
                res.set_content(R"({"error": ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }

        // 获取所有用户信息
        static void GetAllUsers(const Request &req, Response &res)
        {
            try
            {
                // 从数据库中获取所有用户信息
                std::vector<UserDataType> users = UserDBHandler::GetAllUsers();
                LOG_INFO("GetAllUsers: users.size() = %d", users.size());

                // 构造 JSON 响应数据
                json result = json::array();
                LOG_INFO("下面是用户状态检查日志，行数代表用户数量");
                for (const auto &user : users)
                {
                    json item;
                    item["user_id"] = user.user_id;
                    item["username"] = user.username;
                    item["email"] = user.email;
                    item["created_at"] = user.created_at;
                    item["status"] = std::to_string(user.status); // 1表示正常，0表示被封禁
                    LOG_INFO("用户ID: %s, 状态: %d", user.user_id, user.status);
                    result.push_back(item);
                }

                // 返回 JSON 数据
                res.set_content(result.dump(), "application/json");
            }
            catch (const std::exception &ex)
            {
                // 错误处理：返回错误信息
                res.status = 500;
                res.set_content(R"({"error": ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }

        // 删除指定用户
        static void DeleteUser(const Request &req, Response &res)
        {
            try
            {
                // 提取路径参数 user_id
                auto user_id_s = req.path_params.at("user_id");
                size_t user_id = std::stoul(user_id_s);

                // 调用 DBHandler 的 DeleteUser 方法进行删除
                int ret = UserDBHandler::DeleteUser(user_id);
                if (!ret)
                {
                    // 删除失败
                    res.status = 400;
                    res.set_content(R"({"error": "User not found by user_id"})", "application/json");
                    return;
                }

                // 删除成功(包括指定用户不存在的情况)
                // 删除用户后，其图片和帖子和活动的保留情况参照forum.sql文件
                res.set_content(R"({"message": "User deleted successfully"})", "application/json");
            }
            catch (const std::exception &ex)
            {
                // 错误处理：返回错误信息
                res.status = 400;
                res.set_content(R"({"error": ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }

        // 利用用户名搜索用户
        // 注意该接口注册为Get方法，会忽略body请求体，所以需要在URL查询参数中传入username
        static void SearchUserByName(const Request &req, Response &res)
        {
            try
            {
                // 提取请求参数
                std::string username = req.get_param_value("username");

                // 从数据库中搜索用户
                UserDataType users = UserDBHandler::GetUserByName(username);

                // 构造 JSON 响应数据
                json result;
                if (users)
                {
                    result["user_id"] = users.user_id;
                    result["username"] = users.username;
                    result["email"] = users.email;
                    result["created_at"] = users.created_at;
                    result["status"] = std::to_string(users.status); // 1表示正常，0表示被封禁
                    // LOG_INFO("用户ID: %s, 状态: %d", users.user_id, users.status);
                }
                else
                {
                    res.status = 404;
                    res.set_content(R"({"error": "User not found by username"})", "application/json");
                    return;
                }

                // 返回 JSON 数据
                res.set_content(result.dump(), "application/json");
            }
            catch (const std::exception &ex)
            {
                // 错误处理：返回错误信息
                res.status = 500;
                res.set_content(R"({"error": ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }

        // 封禁用户
        static void BlockUser(const Request &req, Response &res)
        {
            try
            {
                // 提取路径参数 user_id
                auto user_id_s = req.path_params.at("user_id");
                size_t user_id = std::stoul(user_id_s);

                // 调用 DBHandler 的 BlockUser 方法进行封禁
                int ret = UserDBHandler::BlockUser(user_id);
                if (!ret)
                {
                    // 封禁失败
                    res.status = 400;
                    res.set_content(R"({"error": "User not found by user_id"})", "application/json");
                    return;
                }

                // 封禁成功
                res.set_content(R"({"message": "User blocked successfully"})", "application/json");
            }
            catch (const std::exception &ex)
            {
                // 错误处理：返回错误信息
                res.status = 400;
                res.set_content(R"({"error": ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }

        // 解封用户
        static void UnblockUser(const Request &req, Response &res)
        {
            try
            {
                // 提取路径参数 user_id
                auto user_id_s = req.path_params.at("user_id");
                size_t user_id = std::stoul(user_id_s);

                // 调用 DBHandler 的 UnblockUser 方法进行解封
                int ret = UserDBHandler::UnblockUser(user_id);
                if (!ret)
                {
                    // 解封失败
                    res.status = 400;
                    res.set_content(R"({"error": "User not found by user_id"})", "application/json");
                    return;
                }

                // 解封成功
                res.set_content(R"({"message": "User unblocked successfully"})", "application/json");
            }
            catch (const std::exception &ex)
            {
                // 错误处理：返回错误信息
                res.status = 400;
                res.set_content(R"({"error": ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }
    };

    class PostHttpHandler
    {
    public:
        // 发表新帖子
        static void UploadPost(const Request &req, Response &res)
        {
            try
            {
                // 提取请求参数
                std::string title = req.get_file_value("title").content;
                std::string content = req.get_file_value("content").content;
                std::string user_id = req.get_file_value("user_id").content;

                // 调用 DBHandler 的 SavePost 方法进行保存
                PostDataType post(user_id, title, content);
                if (!post || !PostDBHandler::SavePost(post))
                {
                    // 保存失败(1.帖子对象内容填充部分和要求；2.数据库操作失败)
                    res.status = 400;
                    res.set_content(R"({"error": "Failed to save post"})", "application/json");
                    return;
                }

                // 保存成功
                res.set_content(R"({"message": "Post saved successfully"})", "application/json");
            }
            catch (const std::exception &ex)
            {
                // 错误处理：返回错误信息
                res.status = 400;
                res.set_content(R"({"error": ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }

        // 获取所有帖子
        static void GetAllPosts(const Request &req, Response &res)
        {
            try
            {
                // 提取sort参数
                std::string sort = req.get_param_value("sort");
                if (sort.empty())
                {
                    sort = "time"; // 默认按创建时间排序
                }

                // 从数据库中获取所有帖子
                std::vector<PostDataType> posts = (sort == "likes") ? PostDBHandler::GetPosts_OrderByLikes() : PostDBHandler::GetPosts_OrderByTime();
                LOG_INFO("GetAllPosts: posts.size() = %d", posts.size());

                // 构造 JSON 响应数据
                json result = json::array();
                for (const auto &post : posts)
                {
                    json item;
                    item["post_id"] = post.post_id;
                    item["user_id"] = post.user_id;
                    item["title"] = post.title;
                    item["content"] = post.content;
                    item["created_at"] = post.created_at;
                    item["likes"] = post.likes;
                    result.push_back(item);
                }

                // 返回 JSON 数据
                res.set_content(result.dump(), "application/json");
            }
            catch (const std::exception &ex)
            {
                // 错误处理：返回错误信息
                res.status = 500;
                res.set_content(R"({"error": ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }

        // 点赞帖子
        static void LikePost(const Request &req, Response &res)
        {
            try
            {
                // 提取路径参数 post_id
                auto post_id_s = req.path_params.at("post_id");
                size_t post_id = std::stoul(post_id_s);
                // 提取请求参数 user_id
                std::string user_id_s = req.get_file_value("user_id").content;
                size_t user_id = std::stoul(user_id_s);

                // 调用 DBHandler 的 LikePost 方法进行点赞
                int ret = PostDBHandler::LikePost(post_id, user_id);
                if (!ret)
                {
                    // 点赞失败(1.已经点过赞；2.帖子不存在)
                    res.status = 400;
                    res.set_content(R"({"error": "Post not found by post_id or user has already liked it"})", "application/json");
                    return;
                }

                // 点赞成功
                res.set_content(R"({"message": "Post liked successfully"})", "application/json");
            }
            catch (const std::exception &ex)
            {
                // 错误处理：返回错误信息
                res.status = 500; // 更改为 500 状态码表示服务器内部错误
                res.set_content(R"({"error":  ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }

        // 删除帖子
        static void DeletePost(const Request &req, Response &res)
        {
            try
            {
                // 提取路径参数 post_id
                auto post_id_s = req.path_params.at("post_id");
                size_t post_id = std::stoul(post_id_s);

                // 调用 DBHandler 的 DeletePost 方法进行删除
                int ret = PostDBHandler::DeletePost(post_id);
                if (!ret)
                {
                    // 删除失败，数据库操作执行失败
                    res.status = 400;
                    res.set_content(R"({"error": "Failed to delete post by post_id"})", "application/json");
                    return;
                }

                // 删除成功
                res.set_content(R"({"message": "Post deleted successfully"})", "application/json");
            }
            catch (const std::exception &ex)
            {
                // 错误处理：返回错误信息
                res.status = 400;
                res.set_content(R"({"error": ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }

        // 搜索帖子（模糊搜索）
        static void SearchPost(const Request &req, Response &res)
        {
            try
            {
                // 提取请求参数
                std::string keyword = req.get_param_value("keyword");

                // 从数据库中搜索帖子
                std::vector<PostDataType> posts = PostDBHandler::FuzzySearchPost(keyword);
                LOG_INFO("SearchPost: posts.size() = %d", posts.size());

                // 构造 JSON 响应数据
                json result = json::array();
                for (const auto &post : posts)
                {
                    json item;
                    item["post_id"] = post.post_id;
                    item["user_id"] = post.user_id;
                    item["title"] = post.title;
                    item["content"] = post.content;
                    item["created_at"] = post.created_at;
                    item["likes"] = post.likes;
                    result.push_back(item);
                }

                // 返回 JSON 数据
                res.set_content(result.dump(), "application/json");
            }
            catch (const std::exception &ex)
            {
                // 错误处理：返回错误信息
                res.status = 500;
                res.set_content(R"({"error": ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }

        // 获取某个用户的所有帖子
        static void GetPostsByUser(const Request &req, Response &res)
        {
            try
            {
                // 提取路径参数 user_id
                auto user_id_s = req.path_params.at("user_id");
                size_t user_id = std::stoul(user_id_s);

                // 从数据库中获取某个用户的所有帖子
                std::vector<PostDataType> posts = PostDBHandler::GetPostsByUserID(user_id);
                LOG_INFO("GetPostsByUser: posts.size() = %d", posts.size());

                // 构造 JSON 响应数据
                json result = json::array();
                for (const auto &post : posts)
                {
                    json item;
                    item["post_id"] = post.post_id;
                    item["user_id"] = post.user_id;
                    item["title"] = post.title;
                    item["content"] = post.content;
                    item["created_at"] = post.created_at;
                    item["likes"] = post.likes;
                    result.push_back(item);
                }

                // 返回 JSON 数据
                res.set_content(result.dump(), "application/json");
            }
            catch (const std::exception &ex)
            {
                // 错误处理：返回错误信息
                res.status = 500;
                res.set_content(R"({"error": ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }
    };

    class CommentHttpHandler
    {
    public:
        // 发表新评论
        static void UploadComment(const Request &req, Response &res)
        {
            try
            {
                // 提取请求参数
                std::string content = req.get_file_value("content").content;
                std::string user_id = req.get_file_value("user_id").content;
                // 提取路径参数 post_id
                auto post_id = req.path_params.at("post_id");

                // 调用 DBHandler 的 SaveComment 方法进行保存
                CommentDataType comment(user_id, post_id, content);
                if (!comment || !CommentDBHandler::SaveComment(comment))
                {
                    // 保存失败(1.评论对象内容填充部分和要求；2.数据库操作失败)
                    res.status = 400;
                    res.set_content(R"({"error": "Failed to save comment"})", "application/json");
                    return;
                }

                // 保存成功
                res.set_content(R"({"message": "Comment saved successfully"})", "application/json");
            }
            catch (const std::exception &ex)
            {
                // 错误处理：返回错误信息
                res.status = 400;
                res.set_content(R"({"error": ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }

        // 获取某个帖子的所有评论
        static void GetCommentsByPost(const Request &req, Response &res)
        {
            try
            {
                // 提取路径参数 post_id
                auto post_id_s = req.path_params.at("post_id");
                size_t post_id = std::stoul(post_id_s);

                // 从数据库中获取某个帖子的所有评论
                std::vector<CommentDataType> comments = CommentDBHandler::GetCommentsByPostID(post_id);
                LOG_INFO("GetCommentsByPost: comments.size() = %d", comments.size());

                // 构造 JSON 响应数据
                json result = json::array();
                for (const auto &comment : comments)
                {
                    json item;
                    item["comment_id"] = comment.comment_id;
                    item["user_id"] = comment.user_id;
                    item["post_id"] = comment.post_id;
                    item["content"] = comment.content;
                    item["created_at"] = comment.created_at;
                    result.push_back(item);
                }

                // 返回 JSON 数据
                res.set_content(result.dump(), "application/json");
            }
            catch (const std::exception &ex)
            {
                // 错误处理：返回错误信息
                res.status = 500;
                res.set_content(R"({"error": ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }

        // 删除评论
        static void DeleteComment(const Request &req, Response &res)
        {
            try
            {
                // 提取路径参数 comment_id
                auto comment_id_s = req.path_params.at("comment_id");
                size_t comment_id = std::stoul(comment_id_s);

                // 调用 DBHandler 的 DeleteComment 方法进行删除
                int ret = CommentDBHandler::DeleteComment(comment_id);
                if (!ret)
                {
                    // 删除失败，数据库操作执行失败
                    res.status = 400;
                    res.set_content(R"({"error": "Failed to delete comment by comment_id"})", "application/json");
                    return;
                }
                // 删除成功
                res.set_content(R"({"message": "Comment deleted successfully"})", "application/json");
            }
            catch (const std::exception &ex)
            {
                // 错误处理：返回错误信息
                res.status = 400;
                res.set_content(R"({"error": ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }
    };

    class EventHttpHandler
    {
    public:
        // 发布新活动
        static void UploadEvent(const Request &req, Response &res)
        {
            try
            {
                // 提取请求参数
                std::string user_id = req.get_file_value("user_id").content;
                std::string title = req.get_file_value("title").content;
                std::string description = req.get_file_value("description").content;
                std::string location = req.get_file_value("location").content;
                std::string event_date = req.get_file_value("event_date").content;
                // 下面两个字段自动填充
                // std::string is_top = req.get_file_value("is_top").content;
                // std::string likes = req.get_file_value("likes").content;

                // 调用 DBHandler 的 SaveEvent 方法进行保存
                EventDataType event(user_id, title, description, location, event_date);
                if (!event || !EventDBHandler::SaveEvent(event))
                {
                    // 保存失败(1.活动对象内容填充部分和要求；2.数据库操作失败)
                    res.status = 400;
                    res.set_content(R"({"error": "Failed to save event"})", "application/json");
                    return;
                }

                // 保存成功
                res.set_content(R"({"message": "Event saved successfully"})", "application/json");
            }
            catch (const std::exception &ex)
            {
                // 错误处理：返回错误信息
                res.status = 400;
                res.set_content(R"({"error": ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }
        // 获取所有活动
        static void GetAllEvents(const Request &req, Response &res)
        {
            try
            {
                // 获取参数
                std::string sort = req.get_param_value("sort");
                if (sort.empty())
                {
                    sort = "time"; // 默认按发布时间排序
                }
                // 从数据库中获取所有活动
                std::vector<EventDataType> events = (sort == "likes") ? EventDBHandler::GetEvents_OrderByLikes() : EventDBHandler::GetEvents_OrderByTime();
                LOG_INFO("GetAllEvents: events.size() = %d", events.size());

                // 构造 JSON 响应数据
                json result = json::array();
                for (const auto &event : events)
                {
                    json item;
                    item["event_id"] = event.event_id;
                    item["user_id"] = event.user_id;
                    item["title"] = event.title;
                    item["description"] = event.description;
                    item["location"] = event.location;
                    item["event_date"] = event.event_date;
                    item["is_top"] = event.is_top;
                    item["likes"] = event.likes;
                    result.push_back(item);
                }

                // 返回 JSON 数据
                res.set_content(result.dump(), "application/json");
            }
            catch (const std::exception &ex)
            {
                // 错误处理：返回错误信息
                res.status = 500;
                res.set_content(R"({"error": ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }
        // 点赞活动
        static void LikeEvent(const Request &req, Response &res)
        {
            try
            {
                // 提取路径参数 event_id
                auto event_id_s = req.path_params.at("event_id");
                size_t event_id = std::stoul(event_id_s);
                // 提取请求参数 user_id
                std::string user_id_s = req.get_file_value("user_id").content;
                size_t user_id = std::stoul(user_id_s);

                // 调用 DBHandler 的 LikeEvent 方法进行点赞
                int ret = EventDBHandler::LikeEvent(event_id, user_id);
                if (!ret)
                {
                    // 点赞失败(1.已经点过赞；2.活动不存在)
                    res.status = 400;
                    res.set_content(R"({"error": "Event not found by event_id or user has already liked it"})", "application/json");
                    return;
                }

                // 点赞成功
                res.set_content(R"({"message": "Event liked successfully"})", "application/json");
            }
            catch (const std::exception &ex)
            {
                // 错误处理：返回错误信息
                res.status = 400;
                res.set_content(R"({"error": ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }
        // 删除活动
        static void DeleteEvent(const Request &req, Response &res)
        {
            try
            {
                // 提取路径参数 event_id
                auto event_id_s = req.path_params.at("event_id");
                size_t event_id = std::stoul(event_id_s);

                // 调用 DBHandler 的 DeleteEvent 方法进行删除
                int ret = EventDBHandler::DeleteEvent(event_id);
                if (!ret)
                {
                    // 删除失败，数据库操作执行失败
                    res.status = 400;
                    res.set_content(R"({"error": "Failed to delete event by event_id"})", "application/json");
                    return;
                }

                // 删除成功
                res.set_content(R"({"message": "Event deleted successfully"})", "application/json");
            }
            catch (const std::exception &ex)
            {
                // 错误处理：返回错误信息
                res.status = 400;
                res.set_content(R"({"error": ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }
        // 模糊搜索活动
        static void SearchEvent(const Request &req, Response &res)
        {
            try
            {
                // 提取请求参数
                std::string keyword = req.get_param_value("keyword");

                // 从数据库中搜索活动
                std::vector<EventDataType> events = EventDBHandler::FuzzySearchEvent(keyword);
                LOG_INFO("SearchEvent: events.size() = %d", events.size());

                // 构造 JSON 响应数据
                json result = json::array();
                for (const auto &event : events)
                {
                    json item;
                    item["event_id"] = event.event_id;
                    item["user_id"] = event.user_id;
                    item["title"] = event.title;
                    item["description"] = event.description;
                    item["location"] = event.location;
                    item["event_date"] = event.event_date;
                    item["is_top"] = event.is_top;
                    item["likes"] = event.likes;
                    result.push_back(item);
                }
                // 返回 JSON 数据
                res.set_content(result.dump(), "application/json");
            }
            catch (const std::exception &ex)
            {
                // 错误处理：返回错误信息
                res.status = 500;
                res.set_content(R"({"error": ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }
        // 获取某个用户的所有活动
        static void GetEventsByUser(const Request &req, Response &res)
        {
            try
            {
                // 提取路径参数 user_id
                auto user_id_s = req.path_params.at("user_id");
                size_t user_id = std::stoul(user_id_s);

                // 从数据库中获取某个用户的所有活动
                std::vector<EventDataType> events = EventDBHandler::GetEventsByUserID(user_id);
                LOG_INFO("GetEventsByUser: events.size() = %d", events.size());

                // 构造 JSON 响应数据
                json result = json::array();
                for (const auto &event : events)
                {
                    json item;
                    item["event_id"] = event.event_id;
                    item["user_id"] = event.user_id;
                    item["title"] = event.title;
                    item["description"] = event.description;
                    item["location"] = event.location;
                    item["event_date"] = event.event_date;
                    item["is_top"] = event.is_top;
                    item["likes"] = event.likes;
                    result.push_back(item);
                }
                // 返回 JSON 数据
                res.set_content(result.dump(), "application/json");
            }
            catch (const std::exception &ex)
            {
                // 错误处理：返回错误信息
                res.status = 500;
                res.set_content(R"({"error": ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }
        // 置顶活动
        static void TopEvent(const Request &req, Response &res)
        {
            try
            {
                // 提取路径参数 event_id
                auto event_id_s = req.path_params.at("event_id");
                size_t event_id = std::stoul(event_id_s);

                // 调用 DBHandler 的 TopEvent 方法进行置顶
                int ret = EventDBHandler::TopEvent(event_id);
                if (!ret)
                {
                    // 置顶失败(1.活动不存在；2.置顶失败)
                    res.status = 400;
                    res.set_content(R"({"error": "Event not found by event_id or failed to top it"})", "application/json");
                    return;
                }
                // 置顶成功
                res.set_content(R"({"message": "Event topped successfully"})", "application/json");
            }
            catch (const std::exception &ex)
            {
                // 错误处理：返回错误信息
                res.status = 400;
                res.set_content(R"({"error": ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }
        // 取消置顶活动
        static void UntopEvent(const Request &req, Response &res)
        {
            try
            {
                // 提取路径参数 event_id
                auto event_id_s = req.path_params.at("event_id");
                size_t event_id = std::stoul(event_id_s);

                // 调用 DBHandler 的 UntopEvent 方法进行取消置顶
                int ret = EventDBHandler::UntopEvent(event_id);
                if (!ret)
                {
                    // 取消置顶失败(1.活动不存在；2.取消置顶失败)
                    res.status = 400;
                    res.set_content(R"({"error": "Event not found by event_id or failed to cancel top it"})", "application/json");
                    return;
                }
                // 取消置顶成功
                res.set_content(R"({"message": "Event cancel topped successfully"})", "application/json");
            }
            catch (const std::exception &ex)
            {
                // 错误处理：返回错误信息
                res.status = 400;
                res.set_content(R"({"error": ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }
    };

    class OtherHttpHandler
    {
    public:
        // 管理员登录
        static void AdminLogin(const Request &req, Response &res)
        {
            try
            {
                // 解析form-data中的口令
                std::string password = req.get_file_value("password").content;
                // 调用 password_hash 中的 VerifyPassword 方法进行验证
                bool ret = PasswordHash::VerifyPassword(password);
                if (!ret)
                {
                    // 如果登录失败（密码错误）
                    res.status = 401;
                    res.set_content(R"({"error": "Invalid admin password"})", "application/json");
                    return;
                }
                // 登录成功，返回成功状态
                res.set_content(R"({"message": "Admin login successfully"})", "application/json");
            }
            catch (const std::exception &ex)
            {
                // 错误处理：返回错误信息
                res.status = 400;
                res.set_content(R"({"error": ")" + std::string(ex.what()) + R"("})", "application/json");
            }
        }
    };
}

#endif // HTTP_HANDLER_HPP